package com.ds.admin.console.service;

import cn.hutool.core.lang.Assert;
import com.ds.common.exception.DaoErrorEnum;
import com.ds.common.exception.SystemException;
import com.ds.common.util.MapstructUtils;
import com.ds.common.web.request.PageParam;
import com.ds.common.web.response.PageBuilder;
import com.ds.common.web.response.PageInfo;
import com.ds.admin.console.param.ProductParam;
import com.ds.admin.console.entity.Product;
import com.ds.admin.console.mapper.ProductMapper;
import com.ds.admin.console.vo.ProductVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class ProductService {

	private final ProductMapper productMapper;

	public Long insert(ProductParam param) {
		Product entity = MapstructUtils.convert(param, Product.class);
		int count = productMapper.insert(entity);
		Assert.isTrue(count > 0, () -> new SystemException(DaoErrorEnum.INSERT_FAILED));
		return entity.getId();
	}

	public Long update(ProductParam param) {
		Product entity = MapstructUtils.convert(param, Product.class);
		int count = productMapper.updateById(entity);
		Assert.isTrue(count > 0, () -> new SystemException(DaoErrorEnum.UPDATE_FAILED));
		return entity.getId();
	}

	public Long delete(Long id) {
		int count = productMapper.deleteById(id);
		Assert.isTrue(count > 0, () -> new SystemException(DaoErrorEnum.DELETE_FAILED));
		return id;
	}

	public ProductVo select(Long id) {
		Product entity = productMapper.selectById(id);
		return MapstructUtils.convert(entity, ProductVo.class);
	}

	public PageInfo<ProductVo> selectPage(PageParam<ProductParam> param) {
		Page<ProductVo> info = PageHelper.startPage(param.getPageNum(), param.getPageSize())
			.doSelectPage(() -> productMapper.selects(param.getParam()));
		return PageBuilder.build(info, info.getPages(), info.getTotal(), info.getPages());
	}

}